package com.rpc.example.nacos;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.rpc.example.IRegitserService;
import com.rpc.example.ServiceInfo;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author Elvis
 * @version 1.0, 2023/3/20
 */
@Slf4j
public class NacosRegisterService implements IRegitserService {
    NamingService naming;

    public NacosRegisterService(String address) {
        try {
            naming = NamingFactory.createNamingService(address);
        } catch (NacosException e) {
          log.error("error: ", e);
        }
    }

    @Override
    public void register(ServiceInfo serviceInfo) throws Exception {
        naming.registerInstance(serviceInfo.getServiceName(), serviceInfo.getServiceAddress(), serviceInfo.getServicePort());
        naming.subscribe(serviceInfo.getServiceName(),event -> {
            if (event instanceof NamingEvent) {
                System.out.println(((NamingEvent) event).getServiceName());
                System.out.println(((NamingEvent) event).getInstances());
            }
        });
    }

    @Override
    public ServiceInfo discovery(String serviceName) throws Exception {
        List<Instance> allInstances = naming.getAllInstances(serviceName);
        List<ServiceInfo> serviceInfos = new ArrayList<>();
        if (allInstances != null && allInstances.size() > 0) {
            for (Instance allInstance : allInstances) {
                ServiceInfo serviceInfo = new ServiceInfo();
                serviceInfo.setServiceAddress(allInstance.getIp());
                serviceInfo.setServicePort(allInstance.getPort());
                serviceInfo.setServiceName(allInstance.getServiceName());
                serviceInfos.add(serviceInfo);
            }
        }

        int size = serviceInfos.size();
        Random random = new Random();
        return serviceInfos.get(random.nextInt(size));
    }

}
